package cn.edu.xmu.javaee.productwebflux.dao;

import cn.edu.xmu.javaee.core.exception.BusinessException;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.javaee.core.util.JacksonUtil;
import cn.edu.xmu.javaee.productwebflux.dao.bo.Product;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Mono;

import java.util.Locale;

@Repository
@Slf4j
@RequiredArgsConstructor
public class ProductDao {

    private final MessageSource messageSource;


    /**
     * 按照id找到产品信息
     * @param shopId 商铺id
     * @param id 产品id
     * @return
     * @throws BusinessException
     */
    public Mono<Product> findById(Long shopId, Long id) throws BusinessException{
        Locale locale = LocaleContextHolder.getLocale();
        if (1L != id) {
            log.debug("findById: shopId={}, id={}", shopId, id);
            String[] objects = new String[] {messageSource.getMessage("productapplication", null, locale), id.toString()};
            throw new BusinessException(ReturnNo.RESOURCE_ID_NOTEXIST, JacksonUtil.toJson(objects));
        } else{
            if (2L != shopId){
                String[] objects = new String[] {"${productapplication}", id.toString(), shopId.toString()};
                throw new BusinessException(ReturnNo.RESOURCE_ID_OUTSCOPE, JacksonUtil.toJson(objects));
            }else {
                return Mono.just(Product.builder().id(1L).name("测试1").originalPrice(100L).originPlace("厦门").categoryId(2L).shopId(2L).productId(100L).build());
            }
        }
    }

}
